using System;
using System.Linq;
using System.Xml.Linq;

namespace Tavis.Tools {
    public static class XElementExtensions {

        public static Uri GetBaseUrl(this XElement element) {
            var xml = XNamespace.Get("http://www.w3.org/XML/1998/namespace");
            var baseAttribute = (from el in element.AncestorsAndSelf()
                                 where el.Attribute(xml + "base") != null
                                 select el.Attribute(xml + "base")).FirstOrDefault();

            if (baseAttribute != null) {
                return new Uri(baseAttribute.Value);
            }

            return null;
        }


        public static ExceptionDetails ReadAsExceptionDetails(this XElement xElement) {

            return new ExceptionDetails() {
                Code = xElement.Element("Code").Value,
                Message = xElement.Element("Message").Value
            };

        }


        public static T ReadAttribute<T>(this XElement element, string name) {
            if (element.Attribute(name) == null) return default(T);
            return (T)Convert.ChangeType(element.Attribute(name).Value, typeof(T));
        }

        public static T ReadAttribute<T>(this XElement element, string name, T defaultValue) {
            if (element.Attribute(name) == null) return defaultValue;
            return (T)Convert.ChangeType(element.Attribute(name).Value, typeof(T));
        }

        public static bool HasAttribute(this XElement element, string name) {
            return element.Attribute(name) != null;
        }

      


    }
}
